<template>
  <view :data-theme="globPrimary">
    <u-navbar
      title="我的余额"
      :immersive="true"
      :border-bottom="false"
      :background="{ background: 'transparent' }"
      back-icon-color="#ffffff"
      title-color="#ffffff"
      :custom-back="onBack"
    >
      <view slot="right" class="navbar-right" @click="$u.route('/pageUser/user/balanceDetails')"
        >明细</view
      >
    </u-navbar>
    <view class="balance-top" :style="{ background: globPrimaryColor }">
      <view class="u-flex u-col-bottom">
        <view class="unit">
          {{ setting.appMoneySymbol }}
        </view>
        <view class="price">
          {{ balance | formatCurrency('') }}
        </view>
      </view>
    </view>
    <view class="balance-wrapper">
      <scroll-view class="balance-scroll" scroll-y>
        <view class="balance-recharge">
          <view class="title">充值</view>
          <view class="list">
            <view class="item" v-for="(item, index) in recharge" :key="item.id">
              <!-- #ifdef H5 -->
              <div class="box" :class="{ active: current == index }" @click="choose(index)">
                <view class="fill">{{ item.balance | formatCurrency('元') }}</view>
                <view class="send" v-if="item.give_balance != 0">{{
                  `充${item.balance}送${item.give_balance}`
                }}</view>
              </div>
              <!-- #endif -->

              <!-- #ifndef H5 -->
              <div
                class="box"
                v-if="current == index"
                :style="{
                  'border-color': globPrimaryColor,
                }"
                @click="choose(index)"
              >
                <view
                  class="fill"
                  :style="{
                    color: globPrimaryColor,
                  }"
                  >{{ item.balance | formatCurrency('元') }}</view
                >
                <view class="send" v-if="item.give_balance != 0">{{
                  `充${item.balance}送${item.give_balance}`
                }}</view>
              </div>
              <div class="box" v-else @click="choose(index)">
                <view class="fill">{{ item.balance | formatCurrency('元') }}</view>
                <view class="send" v-if="item.give_balance != 0">{{
                  `充${item.balance}送${item.give_balance}`
                }}</view>
              </div>
              <!-- #endif -->
            </view>
          </view>
          <view class="list bottom">
            <!-- <view class="item">
							<div class="box"><view class="fill">充值卡</view></div>
						</view> -->
            <view class="input-item">
              <view class="box">
                <text>{{ setting.appMoneySymbol }}</text>
                <u-input
                  v-model="value"
                  type="number"
                  placeholder="输入其他金额"
                  height="100"
                  @click="current = -1"
                  @focus="inputFocus"
                />
              </view>
            </view>
          </view>
          <view class="proportion">注：充值比例{{ proportion }}</view>
        </view>
        <view class="balance-group">
          <u-radio-group v-model="paywayRadio" :active-color="globPrimaryColor" size="44" wrap>
            <u-radio v-for="(item, index) in payway" :name="item" :key="index">
              <view class="radio">
                <u-image
                  width="44rpx"
                  height="44rpx"
                  :src="`/static/images/${paywayConfig[item].img}`"
                ></u-image>
                <text>{{ paywayConfig[item].text }}</text>
              </view>
            </u-radio>
          </u-radio-group>
        </view>
        <view class="balance-checkbox">
          <u-checkbox v-model="checked" size="30" :active-color="globPrimaryColor || ''"
            >我已阅读并同意</u-checkbox
          >
          <text
            @click="
              $u.route('/pages/protocol', {
                key: 'payment',
              })
            "
          >
            《{{ getAgreementTitle('payment') }}》
          </text>
        </view>
      </scroll-view>
    </view>
    <view class="balance-bottom">
      <view class="left">
        实付
        <text>{{ rechargePrice | formatCurrency }}</text>
      </view>
      <edu-button
        class="btn"
        type="primary"
        :disabled="btnDisabled"
        size="medium"
        shape="circle"
        @click="payBtn"
        >去支付</edu-button
      >
    </view>
  </view>
</template>

<script>
import setting from '@/settings/projectSetting.js'
import { pay, isWechat } from '@/utils/pay.js'
import { mapState, mapGetters } from 'vuex'
export default {
  data() {
    return {
      setting,
      value: '',
      total: 0,
      balance: 0,
      recharge: [], // 充值
      current: 0,
      payway: [], // 支付方式
      paywayRadio: '',
      proportion: '',
      paywayConfig: {
        wxpay: {
          text: '微信',
          img: 'order_wechat_icon.png',
        },
        alipay: {
          text: '支付宝',
          img: 'order_zhifubao_icon.png',
        },
      },
      checked: false,
      btnDisabled: true,
    }
  },
  onShow() {
    // 请求余额
    this.$edu.api.getUserBalance().then((res) => {
      const { data } = res
      this.balance = data.balance
      this.payway = data.payway
      this.recharge = data.recharge.public
      this.proportion = res.data.recharge.ratio
      if (!this.$u.test.empty(data.payway)) {
        const list = ['wxpay', 'alipay']
        const set1 = new Set(data.payway)
        const set2 = new Set(list)
        let str = [...set1].filter((x) => set2.has(x))
        str.sort((prev, next) => {
          return list.indexOf(prev) - list.indexOf(next)
        })
        // #ifdef MP-WEIXIN
        // 小程序隐藏支付宝
        str.splice(
          str.findIndex((item) => item == 'alipay'),
          1
        )
        // #endif
        /* #ifdef H5 */
        var ua = window.navigator.userAgent.toLowerCase()
        if (ua.match(/micromessenger/i) == 'micromessenger') {
          str.splice(
            str.findIndex((item) => item == 'alipay'),
            1
          )
        }
        /* #endif */
        this.payway = str
        const val = list.find((k) => str.includes(k))
        this.paywayRadio = val
      }
    })
  },
  computed: {
    ...mapState({
      getGlobOpenid: (state) => state.projectSetting.globOpenid,
    }),
    ...mapGetters({
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      getAgreementTitle: 'projectSetting/getAgreementTitle',
    }),
    rechargePrice() {
      if (this.current != -1) {
        let data = this.recharge.find((item, index) => this.current == index)
        if (this.$u.test.empty(data)) {
          return 0
        } else {
          return data.price
        }
      } else {
        return this.total
      }
    },
    money() {
      let data = this.recharge.find((item, index) => this.current == index)
      if (this.$u.test.empty(data)) {
        return 0
      } else {
        return data.balance
      }
    },
    rechargeId() {
      let data = this.recharge.find((item, index) => this.current == index)
      if (this.$u.test.empty(data)) {
        return 0
      } else {
        return data.id
      }
    },
  },
  watch: {
    value(n) {
      let pop = this.proportion.split(':')
      let num = ((n / pop[1]) * pop[0]).toFixed(2)
      this.total = num
      if (n != '' && this.current == -1 && this.checked) {
        this.btnDisabled = false
      } else {
        this.btnDisabled = true
      }
    },
    current(n) {
      if (n != -1 && this.value == '' && this.checked) {
        this.btnDisabled = false
      } else {
        this.btnDisabled = true
      }
    },
    checked(n) {
      if (n && (this.current != -1 || this.value != '')) {
        this.btnDisabled = false
      } else {
        this.btnDisabled = true
      }
    },
  },
  // 监听页面返回
  onBackPress(options) {
    if (options.from === 'navigateBack') {
      return false
    }
    this.onBack()
    return true
  },
  options: { styleIsolation: 'shared' },
  methods: {
    choose(index) {
      if (this.current == index) return
      this.total = 0
      this.value = ''
      this.btnDisabled = false
      this.value = ''
      this.current = index
    },
    payBtn() {
      if (this.paywayRadio == '') return
      let balance = this.money || this.value
      this.$edu.api
        .createUserRecharge({
          recharge_id: this.rechargeId,
          payment: this.rechargePrice,
          balance: balance,
        })
        .then((res) => {
          let params = {
            order_no: res.data.order_no,
            pay_type: this.paywayRadio,
          }
          // #ifdef MP-WEIXIN
          if (this.getGlobOpenid) {
            params = {
              ...params,
              openid: this.getGlobOpenid,
            }
            this.$edu.api.postOrderPay(params).then((res) => {
              pay(res, this.paywayRadio)
            })
          } else {
            this.$store.dispatch('projectSetting/setGlobWeixinAppid')
          }
          // #endif

          // #ifdef H5
          params = {
            ...params,
            return_url: this.setting.appBaseUrl + '/pageUser/user/balance',
          }
          // 微信公众号支付
          if (isWechat()) {
            if (this.getGlobOpenid) {
              params = {
                ...params,
                openid: this.getGlobOpenid,
              }
              this.$edu.api.postOrderPay(params).then((result) => {
                pay(
                  result,
                  this.paywayRadio,
                  () => {
                    this.$u.route({
                      type: 'switchTab',
                      url: 'pages/user/index',
                    })
                  },
                  () => {
                    this.$u.route({
                      type: 'switchTab',
                      url: 'pages/user/index',
                    })
                  }
                )
              })
            } else {
              this.$store.dispatch('projectSetting/setGlobWeixinAppid')
            }
          } else {
            this.$edu.api.postOrderPay(params).then((res) => {
              pay(res, this.paywayRadio, (res) => {
                let encode = encodeURIComponent(params.return_url)
                let paybody = res.data.paybody + '&redirect_url=' + encode
                location.href = paybody
              })
            })
          }
          // #endif

          // #ifdef APP-PLUS
          this.$edu.api.postOrderPay(params).then((res) => {
            pay(
              res,
              this.paywayRadio,
              () => {
                this.$u.route({
                  type: 'switchTab',
                  url: 'pages/user/index',
                })
              },
              () => {
                this.$u.route({
                  type: 'switchTab',
                  url: 'pages/user/index',
                })
              }
            )
          })
          // #endif
        })
    },
    inputFocus() {
      if (this.value == '') {
        this.btnDisabled = true
      }
    },
    // 返回上一页
    onBack() {
      this.$u.route({ type: 'switchTab', url: 'pages/user/index' })
    },
  },
}
</script>

<style lang="scss">
/* #ifndef H5 */
page {
  background: #f7f7f7;
}
/* #endif */
.navbar-right {
  color: #ffffff;
  font-size: 30rpx;
  margin-right: 30rpx;
}
.balance-top {
  padding-top: 44px;
  height: 350rpx;
  @include bg-color();
  display: flex;
  justify-content: center;
  align-items: center;
  .unit {
    color: #ffffff;
    font-size: 40rpx;
    font-weight: 500;
    line-height: 1;
  }
  .price {
    color: #ffffff;
    font-size: 64rpx;
    font-weight: 500;
    line-height: 1;
  }
}
.balance-wrapper {
  height: calc(100vh - 350rpx - 98rpx);
  .balance-scroll {
    height: 100%;
  }
  .balance-recharge {
    padding: 50rpx 30rpx;
    background-color: #ffffff;
    .proportion {
      margin-top: 40rpx;
      font-size: 28rpx;
      font-weight: 400;
      color: #b7bac1;
    }
    .title {
      font-size: 30rpx;
      font-weight: 400;
      color: $edu-main-color;
      margin-bottom: 10rpx;
    }
    .list {
      display: flex;
      flex-wrap: wrap;
      margin: 0 -9rpx;
      .item {
        padding: 0 9rpx;
        width: 33.33%;
        margin-top: 30rpx;
        .box {
          height: 127rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-direction: column;
          border-radius: 8rpx;
          border: 1rpx solid #ebeef5;
          .fill {
            font-size: 30rpx;
            font-weight: 400;
            color: $edu-content-color;
          }
          .send {
            margin-top: 10rpx;
            font-size: 24rpx;
            font-weight: 400;
            color: #b7bac1;
          }
          &.active {
            @include border-color();
            .fill {
              @include text-color();
            }
          }
        }
      }
    }
    .bottom {
      .item .box {
        height: 100rpx;
      }
      .input-item {
        flex: 1;
        padding: 0 9rpx;
        margin-top: 30rpx;
        .box {
          display: flex;
          align-items: center;
          border-radius: 8rpx;
          padding-left: 40rpx;
          padding-right: 20rpx;
          border: 1rpx solid #ebeef5;
          text {
            margin-right: 15rpx;
            font-size: 36rpx;
            font-weight: 500;
            color: $edu-main-color;
          }
        }
      }
    }
  }
  .balance-group {
    background-color: #ffffff;
    margin-top: 20rpx;
    padding: 0 30rpx;
    .radio {
      display: flex;
      align-items: center;
      text {
        margin-left: 24rpx;
        font-size: 30rpx;
        font-weight: 400;
        color: $edu-content-color;
      }
    }
    .u-radio-group {
      width: 100%;
      .u-radio {
        padding: 30rpx 0;
      }
      /deep/.u-radio__label {
        flex: 1;
      }
      .u-radio {
        flex-direction: row-reverse;
      }
    }
  }
  .balance-checkbox {
    margin-top: 20rpx;
    padding: 0 30rpx;
    display: flex;
    align-items: center;
    height: 120rpx;
    background-color: #fff;
    /deep/.u-checkbox__label {
      font-size: 28rpx;
      margin-right: 0;
    }
    text {
      @include text-color();
      font-size: 28rpx;
    }
  }
}
.balance-bottom {
  height: 98rpx;
  background: #ffffff;
  box-shadow: 0 2rpx 14rpx 0 rgba(0, 0, 0, 0.06);
  padding: 0 30rpx;
  display: flex;
  align-items: center;

  /* #ifdef MP-WEIXIN || APP-PLUS */
  justify-content: space-between;
  /* #endif */
  .left {
    font-size: 26rpx;
    font-weight: 400;
    color: $edu-main-color;
    display: flex;
    align-items: center;
    text {
      margin-left: 10rpx;
      font-size: 32rpx;
      font-weight: 500;
      color: $edu-price-color;
    }
  }
  .btn {
    margin-right: 0;
  }
}

.radio_item {
  height: auto;
  width: 100%;
  overflow: hidden;

  .radio_li {
    margin-top: 60rpx;
    display: flex;
    justify-content: space-between;
    .left_item {
      width: 60%;
      display: flex;
      height: 44rpx;
      .text {
        @include text-color();
        margin-left: 24rpx;
      }
    }
  }
}
</style>
